package org.eyeTopLight.controller;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.io.IoUtil;
import org.eyeTopLight.po.CommonResult;
import org.eyeTopLight.po.initEntity.Goods;
import org.eyeTopLight.service.FrameGoodsService;
import org.eyeTopLight.service.LenGoodsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

@RestController
public class ImageController {

    private static final Logger logger = LoggerFactory.getLogger(ImageController.class);

    @Value("${preFixPath}")
    public String prefixPath;

    @Resource
    FrameGoodsService frameGoodsService;

    @Resource
    LenGoodsService lenGoodsService;

    /**（已完成）
     * 获取某个商品指定位置的图片，注意这里是post方法
     * @param response
     * @param paramMap 含有三个参数，goods_id,goods_urlIndex表示要获取该商品展示的第几张图片，goods_symbol表示所属大分类
     */
   @PostMapping(value = "/image/getImageByIdAndIndex")
    public void getImageByIdAndIndex(HttpServletResponse response,
                                     @RequestBody Map<String,Object> paramMap) {
       Integer goods_id = (Integer) paramMap.get("goods_id");
       Integer goods_urlIndex = (Integer) paramMap.get("goods_urlIndex");
       String symbol = (String) paramMap.get("goods_symbol");
       Goods goods = null;
       try {
           goods = symbol.equals("frame") ? frameGoodsService.getGoodsByPK(goods_id) : lenGoodsService.getGoodsByPK(goods_id);
       } catch (Exception e) {
           logger.error("数据库+" + symbol + "Goods表操作失败", e);
           return;
       }
       String dateTime = goods.getGoods_updateDate();
       String fileName = goods.getImageUrlAtIndex(goods_urlIndex);
       if (null == fileName || fileName.isEmpty()) {
           logger.error("商品id:" + goods_id + "第" + goods_id + "张图片不存在");
           return;
       }
       String filePath = prefixPath + "/" + symbol + "/" + dateTime + "/" + fileName;
       File imgFile = new File(filePath);
       FileInputStream fin = null;
       OutputStream output = null;
       response.setCharacterEncoding("utf-8");
       response.setContentType("application/octet-stream");
       response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
       response.setHeader("Content-type", "application/octet-stream");
       try {
           output = response.getOutputStream();
           fin = new FileInputStream(imgFile);
           byte[] arr = new byte[1024 * 10];
           int n;
           while ((n = fin.read(arr)) != -1) {
               output.write(arr, 0, n);
           }
           output.flush();
       } catch (IOException e) {
           logger.error("读取图片失败", e);
       }
       try {
           output.close();
           fin.close();
       } catch (IOException e) {
           e.printStackTrace();
       }
   }

    /**（待开发）
     * 获取某个商品详情指定位置的图片，注意这里是post方法
     * @param response
     * @param paramMap 含有三个参数，goods_id,goods_DetailsIndex表示要获取该商品详情页的第几张图片，goods_symbol表示所属大分类
     */
    @PostMapping(value = "/image/getDetailsImageByIdAndIndex")
    public void getDetailsImageByIdAndIndex(HttpServletResponse response,
                                     @RequestBody Map<String,Object> paramMap) {

    }

    /**
     * 获取首页主副广告位图片数量
     * @param adPosition main or sub
     * @return response 图片数量
     */
    @GetMapping(value = "/image/getAdvertiseImagesCount")
    public CommonResult<Integer> getAdvertiseImagesCount(@RequestParam(value = "adPosition") String adPosition){
        String filePath = prefixPath + "/adPosition/" + adPosition;
        Integer imageCount = new File(filePath).listFiles().length;
        return new CommonResult<Integer>(200, "success", imageCount);
    }

    @PostMapping(value = "/image/getAdvertiseImageByIdAndIndex")
    public void getAdvertiseImageByIdAndIndex(HttpServletResponse response,
                                              @RequestBody Map<String,Object> paramMap){
        String adPosition = (String) paramMap.get("adPosition");
        Integer index = (Integer) paramMap.get("index");
        String filePath = prefixPath + "/adPosition/" + adPosition;
        File imgFile = new File(filePath).listFiles()[index];
        FileInputStream fin = null;
        OutputStream output = null;
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;fileName=" + imgFile.getName());
        response.setHeader("Content-type", "application/octet-stream");
        try {
            output = response.getOutputStream();
            fin = new FileInputStream(imgFile);
            byte[] arr = new byte[1024 * 10];
            int n;
            while ((n = fin.read(arr)) != -1) {
                output.write(arr, 0, n);
            }
            output.flush();
        } catch (IOException e) {
            logger.error("读取图片失败", e);
        }
        try {
            output.close();
            fin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
